import pandas as pd
import numpy as np
import xgboost as xgb
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, classification_report
from sklearn.preprocessing import StandardScaler

# 模拟数据生成
np.random.seed(42)

# 生成100条数据
num_samples = 100

# 定义每个维度的数据范围
age = np.random.randint(18, 70, num_samples)
income = np.random.randint(20000, 120000, num_samples)  # 年收入
credit_score = np.random.randint(300, 850, num_samples)  # 信用评分
loan_amount = np.random.randint(1000, 50000, num_samples)  # 贷款金额
loan_term = np.random.randint(12, 360, num_samples)  # 贷款期限（以月为单位）
years_at_job = np.random.randint(0, 40, num_samples)  # 工作年限
dti = np.random.uniform(0.1, 0.6, num_samples)  # 债务收入比
default_history = np.random.choice([0, 1], num_samples)  # 违约历史（0表示无，1表示有）

# 创建数据框
data = pd.DataFrame({
    'Age': age,
    'Income': income,
    'Credit Score': credit_score,
    'Loan Amount': loan_amount,
    'Loan Term': loan_term,
    'Years at Job': years_at_job,
    'Debt-to-Income Ratio': dti,
    'Default History': default_history
})

# 查看数据
print(data.head())  # 输出前五行，检查数据是否正确加载

# 准备数据
X = data.drop(columns=["Default History"])  # 特征
y = data["Default History"]  # 标签

# 特征缩放：标准化特征
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)

# 分割训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.2, random_state=42)

# 初始化XGBoost分类器
model = xgb.XGBClassifier(
    objective='binary:logistic',  # 二分类问题
    eval_metric='logloss',  # 损失函数
    max_depth=3,  # 树的最大深度
    learning_rate=0.1,  # 学习率
    n_estimators=100,  # 树的个数
    random_state=42
)

# 训练模型
model.fit(X_train, y_train)

# 用训练好的模型进行预测
y_pred = model.predict(X_test)

# 评估模型
accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy: {accuracy:.4f}")
print("Classification Report:")
print(classification_report(y_test, y_pred))
